package com.gmzg.gmzgoffice.works;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.gmzg.gmzgoffice.R;
import com.gmzg.gmzgoffice.entity.Attendance;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class SignActivity extends AppCompatActivity implements AMapLocationListener, AMap.OnCameraChangeListener {

    public static final String POINAME = "poiname";
    public static final String ADDRESS = "address";
    public static final String TIME = "time";
    public static final String COMPANY = "company";
    public static final int REQUEST_OK = 110;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.mapview)
    MapView mMapview;
    @BindView(R.id.sign_address)
    TextView mSignAddress;
    @BindView(R.id.sign_time)
    TextView mSignTime;
    @BindView(R.id.sign_organization)
    TextView mSignOrganization;
    @BindView(R.id.sign_visit_object_tv)
    TextView mSignVisitObjectTv;
    @BindView(R.id.sign_detail_time)
    TextView mSignDetailTime;
    @BindView(R.id.sign_ll)
    LinearLayout mSignLl;
    @BindView(R.id.sign_company)
    TextView mSignCompany;
    @BindView(R.id.activity_sign)
    LinearLayout mActivitySign;
    @BindView(R.id.sign_num)
    TextView mSignNum;
    private AMapLocationClient mapLocationClient;
    private AMapLocationClientOption mLocationClientOption;
    private UiSettings mSettings;
    private AMap mMap;
    private String mAddress;
    private long mUptimeMillis;
    private boolean isFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ButterKnife.bind(this);
        mToolbarTitle.setText("签到");
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        //给页面控件赋值
        initData();

        //使用高德定位信息
        initLocation();
        //初始化高德地图信息
        mMapview.onCreate(savedInstanceState);
        initMapInfo();
        //在子线程中开始定位
        startLocation();


    }

    private void startLocation() {
        new Thread() {
            @Override
            public void run() {
                //启动定位
                if (mapLocationClient != null) {
                    mapLocationClient.startLocation();
                }
            }
        }.start();

    }

    private void initData() {
        mUptimeMillis = System.currentTimeMillis();
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        Date date = new Date(mUptimeMillis);
        String time =  df.format(date);
        mSignTime.setText(time);
        // TODO: 2016/11/8  为当前企业赋值
        mSignCompany.setText("GMZG");
        df = new SimpleDateFormat("HH:mm");
        time = df.format(date);
        mSignDetailTime.setText(time);

        //获取签到次数

        getSignNum();
    }

    private void initMapInfo() {
        if (mMap == null) {
            mMap = mMapview.getMap();
            mSettings = mMap.getUiSettings();
            mSettings.setZoomControlsEnabled(false);
            mSettings.setMyLocationButtonEnabled(false);
            mSettings.setAllGesturesEnabled(false);
//            mMap.setMyLocationEnabled(true);
//            mMap.setLocationSource(this);
        }
    }

    private void initLocation() {
        //初始化定位
        mapLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mapLocationClient.setLocationListener(this);
        mLocationClientOption = new AMapLocationClientOption();
        mLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置单次定位
        mLocationClientOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果
        mLocationClientOption.setOnceLocationLatest(true);
        //给定位客户端对象设置定位参数
        mapLocationClient.setLocationOption(mLocationClientOption);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    //定位结果的接口回调
    @Override
    public void onLocationChanged(AMapLocation location) {
        if (location != null) {
            if (location.getErrorCode() == 0) {
                //解析定位结果
                double latitude = location.getLatitude();//获取纬度
                double longitude = location.getLongitude();//获取经度
                String poiName = location.getPoiName();
                mAddress = location.getAddress();
                //获取定位时间
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(location.getTime());
                df.format(date);
                if (!TextUtils.isEmpty(poiName)) {
                    mSignAddress.setText(poiName);
                } else {
                    mSignAddress.setText(mAddress);
                }
                LatLng latLng = new LatLng(latitude, longitude);
                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 15);
                mMap.addMarker(new MarkerOptions().
                        position(latLng).
                        title(poiName));
                mMap.animateCamera(update);
                mMap.setOnCameraChangeListener(this);
                isFlag = true;

            } else {
                Log.d("AmapError", "location Error, ErrCode:"
                        + location.getErrorCode() + ", errInfo:"
                        + location.getErrorInfo());
            }

        Log.d("ddddddddd", "onLocationChanged: ");
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        startLocation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapview.onPause();
        if (mapLocationClient != null) {
            mapLocationClient.stopLocation();
        }
    }

    //MapView的可视区域发生变化时，回调的接口
    @Override
    public void onCameraChange(CameraPosition position) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition position) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapview.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapview.onResume();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapview.onSaveInstanceState(outState);
    }

    //签到的点击事件
    @OnClick(R.id.sign_ll)
    public void onClick() {
        if (isFlag){
            String visitObject = mSignVisitObjectTv.getText().toString().trim();
            if (!TextUtils.isEmpty(visitObject)) {
                Intent intent = new Intent(this, SignDetailActivity.class);
                //将定位的地址和签到时间发送到签到的详细界面
                Bundle bundle = new Bundle();
                bundle.putLong(TIME, mUptimeMillis);
                bundle.putString(ADDRESS, mAddress);
                bundle.putString(POINAME, mSignAddress.getText().toString());
                bundle.putString(COMPANY, mSignCompany.getText().toString());
                intent.putExtra("bundle", bundle);
                startActivityForResult(intent, REQUEST_OK);
            } else {
                Toast.makeText(this, "拜访对象不能为空", Toast.LENGTH_SHORT).show();
            }
        }else {
            Toast.makeText(this, "定位还未成功,请稍等...", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_OK && resultCode == RESULT_OK) {
            SharedPreferences nums = getSharedPreferences("signnum", MODE_PRIVATE);
            int  num = nums.getInt("num", 0);

            if (num != 0) {
                mSignNum.setText("今天已签到"+num+"次");
                Log.d("aaaa", "onActivityResult进去: "+num);
            }else {
                getSignNum();
            }
            Log.d("aaaa", "onActivityResult: ");

        }
    }

    private void getSignNum() {
        new BmobQuery<Attendance>().findObjects(new FindListener<Attendance>() {
            @Override
            public void done(List<Attendance> list, BmobException e) {
                if (e == null) {
                    if (list != null) {
                        mSignNum.setText("今天已签到"+list.size()+"次");
                    }
                }
            }
        });
    }
}
